﻿import { Guid } from '../common';
let uploads = require("../domain/old_ldc/server/modules/services/uploads-service");
import { getSyncURIFromPUTReq, doResourcesPut } from "../domain/old_ldc/server/routes_controller";
import { IEntityObject } from 'tiny-entity/tinyDB';

export class CloudSyncService {
    constructor() {
    }
    /**
     * 添加到上传云服务器同步队列
     * @param  {IEntityObject} entity 需要同步的数据实体
     * @param  {string} storeId 店铺id
     * @param {boolean} 不需要entity的主键Id
     */
    saveUploads(entity: IEntityObject, storeId: string, noId?: boolean, urlS?: string) {
        let header = {
            "mpj-sync-resource-version": (new Date()).getTime(),
            "content-type": "application/json",
            "token": "V0VJWElOOiQqJTp3ZWl4aW4xMjM0NTZAIyQ="
        };
        delete (<any>entity).sqlTemp;
        let url = '/api/stores/' + storeId + '/' + entity.toString().toLowerCase();
        if (urlS) url = '/api/stores/' + storeId + '/' + urlS;
        if (!noId) url = url + '/' + entity.id;
        uploads.saveUploads(url, null, header, entity);
    }

    DomainDataSync(pkg: DataSyncPackageStruct, storeId: string) {
        let res: resources = {
            headers: {
                "mpj-sync-packed": pkg.packageId,
                "mpj-sync-resource-version": pkg.resourceVersion,
                "mpj-sync-terminal-bind-id": pkg.terminalBindId,
                // "mpj-sync-terminal-bind-id": "",
                "mpj-sync-time-expire": pkg.timeExpire,
                "mpj-sync-single-package": ""
            },
            params: {
                resEntity: pkg.data.entityName,
                resId: pkg.data.id,
                storeId: storeId
            },
            body: pkg.data.body
        };
        doResourcesPut(res, null, null, true).then(() => {
            console.log("doResourcesPut finsh!");
        });
    }

    /**
     * 同步数据到其他Pos端
     * 
     * @param {DataSyncStruct[]} children
     * @param {string} storeId
     * @param {string} terminalName
     * @param {any} [pkg]
     * 
     * @memberOf CloudSyncService
     */
    DomainDataSyncPackage(children: DataSyncStruct[], option: DataSyncOption, pkg?) {
        let pkgId = Guid.GetGuid();

        let res: any = {};
        if (pkg) {
            res = {
                params: {
                    resEntity: "sync-packages",
                    resId: pkgId,
                    storeId: option.storeId
                },
                headers: {
                    "mpj-sync-ensure-ldc-arrival": "true",
                    "mpj-sync-single-package": "packaged",
                    // "mpj-sync-terminal-bind-id": option.terminal.id,
                    "mpj-sync-terminal-bind-id": "fbs",
                    "mpj-sync-time-expire": getLocalTime(3)
                },
                body: {
                    id: pkgId,
                    name: pkg.name,
                    store: { id: option.storeId },
                    storeId: option.storeId,
                    terminalId: "fbs",
                    type: pkg.type,
                    userName: option.user.name,
                    children: []
                }
            }
        }


        for (let item of children) {
            if (pkg) {
                let type = item.entityName;
                if (type == "tableParty") type = "tableParties";
                if (type == "tables") type = "deskTable";

                res.body.children.push({
                    obj: item.body,
                    resourceVersion: new Date().getTime(),
                    timeExpire: getLocalTime(3),
                    type: item.entityName,
                    terminalId: "fbs",
                    uri: "/api/stores/" + option.storeId + "/" + type + "/" + item.id
                });
            }
            else {
                let pkgItem: DataSyncPackageStruct = {
                    packageId: null,
                    resourceVersion: new Date().getTime(),
                    // terminalBindId: option.terminal.id,
                    terminalBindId: "fbs",
                    data: item
                }
                //取3天后
                pkgItem.timeExpire = getLocalTime(3);

                this.DomainDataSync(pkgItem, option.storeId);
            }
        }

        if (pkg) {
            doResourcesPut(res, null, null, true).then(() => {
                console.log("DomainDataSyncPackage doResourcesPut finsh!");
            });
        }
    }
}

function getLocalTime(addNum) {
    let today, ms, thatDay;
    today = new Date().getTime();
    ms = today + addNum * 24 * 60 * 60 * 1000;
    return ms
}

export interface DataSyncStruct {
    id: string;
    entityName: string;
    body: any;
}

export interface DataSyncPackageStruct {
    data: DataSyncStruct;
    packageId: string;
    resourceVersion: number;
    timeExpire?: number;
    terminalBindId: string;
}

export interface DataSyncOption {
    storeId: string;
    terminal: { id: string, name: string },
    user: { id: string, name: string }
}

interface resources {
    body: any;
    headers: any;
    params: any;
}